//
//  TTCalculatorKeyboardView.m
//  TaoTuo
//
//  Created by admin on 2020/2/5.
//  Copyright © 2020 admin. All rights reserved.
//

#import "TTCalculatorKeyboardView.h"
#import "TTCaculatorKeyboardViewCell.h"

static NSString *cellID = @"keyboardCell";

@interface TTCalculatorKeyboardView ()<UICollectionViewDelegate, UICollectionViewDataSource>

@property (nonatomic, strong) UICollectionView *collectionView;
@property (nonatomic, strong) NSArray *dataArray;

@end

@implementation TTCalculatorKeyboardView

+ (instancetype)keyboardViewWithFrame:(CGRect)frame
{
    TTCalculatorKeyboardView *view = [[self alloc] initWithFrame:frame];
    view.dataArray = @[@"1", @"2", @"3", @"delete_keyboard", @"4", @"5", @"6", @"0", @"7", @"8", @"9", @"."];
    view.backgroundColor = [UIColor redColor];
    [view.collectionView reloadData];
    return view;
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return self.dataArray.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    TTCaculatorKeyboardViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:cellID forIndexPath:indexPath];
    cell.title = self.dataArray[indexPath.row];
    return cell;
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    NSString *title = self.dataArray[indexPath.row];
    if ([title isEqualToString:@"delete_keyboard"]) {
        title = @"";
    }
    if ([self.delegate respondsToSelector:@selector(calculatorKeyboardView:selectString:)]) {
        [self.delegate calculatorKeyboardView:self selectString:title];
    }
}

- (UICollectionView *)collectionView
{
    if (!_collectionView) {
        CGFloat w = floor((self.width - 3) / 4);
        UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
        layout.itemSize = CGSizeMake(w, w);
        layout.minimumLineSpacing = 1;
        layout.minimumInteritemSpacing = 1;
        
        _collectionView = [[UICollectionView alloc] initWithFrame:self.bounds collectionViewLayout:layout];
        _collectionView.backgroundColor = [UIColor whiteColor];
        _collectionView.delegate = self;
        _collectionView.dataSource = self;
        [_collectionView registerClass:[TTCaculatorKeyboardViewCell class] forCellWithReuseIdentifier:cellID];
        [self addSubview:_collectionView];
        [_collectionView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.edges.equalTo(self);
        }];
    }
    return _collectionView;
}

@end
